<!--
 * @Author: Rain
 * @Date: 2021-11-21 14:53:46
 * @LastEditTime: 2023/10/30 21:29:41
 * @Description: Do Something
-->
<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div class="flex items-center flex-end w-full search">
        <!-- 搜索 -->
        <!-- <label class="el-form-item-label">题目</label> -->
        <el-input
          v-model="query.exam"
          clearable
          placeholder="题目"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.atmrId"
          placeholder="请选择"
          clearable
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :label="item.atmrName"
            :value="item.id"
          />
        </el-select>
        <rrOperation :crud="crud" />
        <crudOperation :permission="permission" @upload="dialogVisible = true" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="题目" prop="exam">
            <el-input v-model="form.exam" style="width: 370px" placeholder="题目..." />
          </el-form-item>
          <!-- <el-form-item label="测试类型" prop="atmrId">
            <el-select
              v-model="form.atmrId"
              filterable
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item | optionFitler(dict.test_type)"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="题型" prop="examTypeId">
            <el-select
              v-model="form.examTypeId"
              filterable
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in examTypeList"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选项" prop="chose">
            <el-input
              v-model="form.chose"
              style="width: 370px"
              type="textarea"
              placeholder="选项"
            />
          </el-form-item>
          <el-form-item label="答案">
            <el-input v-model="form.answer" style="width: 370px" placeholder="答案..." />
          </el-form-item>
          <el-form-item label="分值" prop="score">
            <el-input-number
              v-model="form.score"
              style="width: 370px"
              placeholder="分值"
            />
          </el-form-item>
          <el-form-item label="是否启用" prop="status">
            <el-select
              v-model="form.status"
              filterable
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in dict.advert_status"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
          >确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        :fit="true"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="#" />
        <el-table-column prop="exam" label="题目" show-overflow-tooltip />
        <el-table-column prop="chose" label="选项" align="center" />
        <el-table-column prop="answer" label="答案" align="center" />
        <el-table-column prop="score" label="分值" align="center" />
        <!-- <el-table-column prop="atmrId" label="测试类型" align="center">
          <template slot-scope="{ row }">
            <div>
              {{ row.atmrId | examFitler(typeList, dict.test_type) }}
            </div>
          </template>
        </el-table-column> -->
        <el-table-column prop="examTypeId" label="题型" align="center">
          <template slot-scope="{ row }">
            <div>
              {{ row.examTypeId | typeFitler(examTypeList) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="是否启用" align="center">
          <template slot-scope="scope">
            {{ dict.label.advert_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkPer(['admin', 'examInfo:edit', 'examInfo:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog title="导入试题" :visible.sync="dialogVisible" width="400px">
      <el-form ref="uploadForm" :model="uploadForm" label-width="80px" :rules="upRules">
        <el-form-item label="测试内容" prop="atmrId">
          <el-select v-model="uploadForm.atmrId" placeholder="选择测试内容">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.atmrName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件" prop="file">
          <el-upload
            class="upload-demo"
            accept=".xls,.csv"
            action="/api/examInfo/upload"
            :auto-upload="false"
            :on-change="uploadFile"
          >
            <div class="flex items-center">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xlxs/csv文件</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadAction">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudExamInfo from '@/api/examInfo'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import rrOperation from '@crud/RR.operation'
import udOperation from '@crud/UD.operation'

const defaultForm = {
  id: null,
  exam: null,
  answer: null,
  atmrId: null,
  score: null,
  chose: null,
  status: null,
  examTypeId: null,
  isOnly: null,
  description: null,
  title: null
}
export default {
  name: 'ExamInfo',
  components: { pagination, crudOperation, rrOperation, udOperation },
  filters: {
    typeFitler(value, typeList) {
      const item = typeList.find((item) => item.id * 1 === value * 1)
      return item && item.typeName
    },
    examFitler(value, typeList, list) {
      const item = typeList.find((item) => item.id * 1 === value * 1)
      if (item) {
        const { atmrType, atmrName } = item
        const type = list.find((i) => i.value === atmrType)
        return type && `${atmrName}-${type.label}`
      }
    },
    optionFitler(item, list) {
      const { atmrName, atmrType } = item
      const type = list.find((i) => i.value === atmrType)
      return type && `${atmrName}-${type.label}`
    }
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['advert_status', 'test_type'],
  cruds() {
    return CRUD({
      title: '试题管理',
      url: 'api/examInfo',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudExamInfo },
      optShow: {
        add: false,
        del: false,
        reset: true,
        upload: false
      }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'examInfo:add'],
        edit: ['admin', 'examInfo:edit'],
        del: ['admin', 'examInfo:del']
      },
      rules: {
        exam: [{ required: true, message: '题目不能为空', trigger: 'blur' }],
        // atmrId: [{ required: true, message: '测试类型不能为空', trigger: 'blur' }],
        score: [{ required: true, message: '分值不能为空', trigger: 'blur' }],
        chose: [{ required: true, message: '选项不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '是否可用不能为空', trigger: 'blur' }],
        examTypeId: [{ required: true, message: '题型编号不能为空', trigger: 'blur' }]
      },
      queryTypeOptions: [
        { key: 'exam', display_name: '题目' }
        // { key: 'atmrId', display_name: '测试类型' }
      ],
      typeList: [],
      examTypeList: [],
      dialogVisible: false,
      uploadForm: {
        atmrId: '',
        file: null
      },
      upRules: {
        atmrId: [{ required: true, message: '请选择测试内容', trigger: 'blur' }],
        file: [{ required: true, message: '请选择要上传的文件', trigger: 'blur' }]
      }
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.uploadForm = {
          atmrId: '',
          file: null
        }
      }
    }
  },
  mounted() {
    // this.queryTestType()
    this.queryExamType()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      const { params } = this.$route
      const { databaseId } = params
      if (databaseId) {
        this.query['examDatabaseId'] = databaseId
      }
      return true
    },
    // 查询测试类型
    queryTestType() {
      this.$http.get(`/api/atmr`).then((_) => {
        const { content } = _
        this.typeList = content
      })
    },
    // 查询题型
    queryExamType() {
      this.$http.get(`/api/examType`).then((_) => {
        const { content } = _
        this.examTypeList = content
      })
    },
    uploadAction() {
      this.$refs['uploadForm'].validate((flag) => {
        const formData = new FormData()
        formData.append('file', this.uploadForm.file)
        this.$http({
          method: 'POST',
          url: `/api/examInfo/upload?atmrId=${this.uploadForm.atmrId}`,
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData
        }).then((_) => {
          this.dialogVisible = false
          this.crud.toQuery()
        })
      })
    },
    uploadFile(e) {
      const { raw } = e
      this.uploadForm.file = raw
    }
  }
}
</script>

<style scoped lang="scss"></style>
